package web;

import com.fasterxml.jackson.databind.ObjectMapper;
import service.AddUserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class CheckUserServlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            System.out.println("CheckUserServlet服务器接收到客户端请求。。。");
            //1.接收前端数据
            String username = req.getParameter("username");
            //2.创建一个map对象，给map中设置内容
            Map<String, Object> map = new HashMap<>();
            //3.在数据库中对用户名进行查询
            boolean flag = new AddUserService().CheckUserService(username);
            if(flag){
                map.put("pass", true);
                map.put("msg", "用户名可以注册");
            }else{
                map.put("pass",false);
                map.put("msg", "已存在该用户名，请更换注册用户名");
            }
            //4 map转成json返回给前台
            ObjectMapper om = new ObjectMapper();
            String mapJson = om.writeValueAsString(map);
            //5 json数据返回给前台
            resp.getWriter().println(mapJson);
            System.out.println(mapJson);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
